<?php

/**
 * Виджет MAP
 * 
 * @author Kosty Ryabichenko <k.ryabichenko@gmail.com>
 * @version 1.0
 */
class MapWidget extends CWidget {

    public function init() {
        
        $settingsMap = SettingsMap::model()->find();     
        $show_per_page = json_decode($settingsMap->show_per_page,1);
        $search = Yii::app()->session->get("searchParams");      
        
        
        if(in_array(Yii::app()->params->page->id, $show_per_page)){
            
            if(!empty($search)){
                $criteria = new CDbCriteria;
                
                if(!empty($search['type_id'])){
                    $criteria->addCondition("type_id = ".$search['type_id']."");
                }

                if(!empty($search['guests'])){
                    $criteria->addCondition("guests = ".$search['guests']."");
                }

                $from = !empty($search['inputPriceFrom']) ? $search['inputPriceFrom'] : Flat::getPriceFromCity($search['city_id'], 'min');
                $to = !empty($search['inputPriceTo']) ? $search['inputPriceTo'] : Flat::getPriceFromCity($search['city_id'], 'max');            
                $criteria->addBetweenCondition("price", $from, $to);

                $criteria->addCondition("is_active = 1");
                
                $flats = Flat::model()->findAll($criteria);
                
            } else {
                $flats = Flat::model()->findAll('is_active = 1');
            }
            
            $this->render('map', array(
                'settingsMap' => $settingsMap,
                'geo' => $this->getGeo(),
                'flats' => $flats,
            ));
            
        }
    }
    
    private function getGeo(){
        $geo = Yii::app()->params['geo'];
        
        // если в searchParams указан город и он совпадает в текушей страницей
        $page = Yii::app()->params['page'];
        $searchParams = Yii::app()->session->get("searchParams");
        if(!empty($searchParams)){
            $city = City::model()->findByPk($searchParams['city_id']);
            if($page->url == $city->url){
                $geo['lat'] = $city->lat;
                $geo['lng'] = $city->lng;
            }
        }
        
        return $geo;
    }

    public function run() {
        // этот метод будет вызван внутри CBaseController::endWidget()
    }

}

?>
